package com.ctshk.rpc.order.localfun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.OrderCollectionStatus;
import com.ctshk.common.enums.SystemBusinessType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.finance.req.bill.BillOperateRefundReq;
import com.ctshk.rpc.finance.service.IFinanceBillService;
import com.ctshk.rpc.order.localfun.dto.LocalFunOrderCollectionDTO;
import com.ctshk.rpc.order.localfun.entity.LocalFunOrder;
import com.ctshk.rpc.order.localfun.entity.LocalFunOrderCollection;
import com.ctshk.rpc.order.localfun.mapper.LocalFunOrderCollectionMapper;
import com.ctshk.rpc.order.localfun.mapper.LocalFunOrderMapper;
import com.ctshk.rpc.order.localfun.req.LocalFunOrderCollectionConfirmationReq;
import com.ctshk.rpc.order.localfun.req.LocalFunOrderCollectionReq;
import com.ctshk.rpc.order.localfun.service.ILocalFunOrderCollectionService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 门票收款明细 服务实现类
 * </p>
 *
 * @author 张志朋
 * @since 2021-02-24
 */
@Slf4j
@DubboService
public class LocalFunOrderCollectionServiceImpl extends ServiceImpl<LocalFunOrderCollectionMapper, LocalFunOrderCollection> implements ILocalFunOrderCollectionService {

    @Autowired
    private LocalFunOrderCollectionMapper scenicOrderCollectionMapper;

    @Autowired
    private LocalFunOrderMapper localFunOrderMapper;
    @DubboReference
    private ISysUserService iSysUserService;
    @DubboReference
    private IFinanceBillService iFinanceBillService;

    @Override
    public Result<List<LocalFunOrderCollectionDTO>> list(LocalFunOrderCollectionReq scenicOrderCollectionReq) {
        QueryWrapper<LocalFunOrderCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted",0);
        queryWrapper.eq("order_id",scenicOrderCollectionReq.getOrderId());
        LocalFunOrder localFunOrder = localFunOrderMapper.selectById(scenicOrderCollectionReq.getOrderId());
        List<LocalFunOrderCollection> list = scenicOrderCollectionMapper.selectList(queryWrapper);

        List<LocalFunOrderCollectionDTO> orderCollectionDTOS = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            for(LocalFunOrderCollection scenicOrderCollection : list){
                LocalFunOrderCollectionDTO scenicOrderTouristDTO = EntityUtil.copy(scenicOrderCollection,LocalFunOrderCollectionDTO.class);
                UserDTO userDTO = null;
                try {
                    userDTO = iSysUserService.loadUserByParam(localFunOrder.getCreateId(), 1);
                    scenicOrderTouristDTO.setSalerName(userDTO.getUsername() + "/" + userDTO.getDept());
                } catch (Exception e) {
                    log.error("获取用户信息错误：{}",e.getMessage());
                }
                scenicOrderTouristDTO.setId(scenicOrderCollection.getId());
                scenicOrderTouristDTO.setCollectionAmount(scenicOrderCollection.getCollectionAmount());
                scenicOrderTouristDTO.setCurrency(scenicOrderCollection.getCurrency());
                orderCollectionDTOS.add(scenicOrderTouristDTO);
            }
        }
        return Result.success(orderCollectionDTOS);
    }

    @Override
    public Result<Long> confirmation(LocalFunOrderCollectionConfirmationReq scenicOrderCollectionConfirmationReq, TokenUser user) {
        if (scenicOrderCollectionConfirmationReq == null) {
            //收款记录不存在
            throw new BusinessException(SystemError.LOCAL_FUN_18006);
        }
        if (scenicOrderCollectionConfirmationReq.getStatus() == null || scenicOrderCollectionConfirmationReq.getStatus() != OrderCollectionStatus.REJECT.getCode()) {
            // 收款记录的状态必须是驳回，才能再次确认
            throw new BusinessException(SystemError.LOCAL_FUN_18007);
        }
        QueryWrapper<LocalFunOrderCollection> scenicOrderCollectionQueryWrapper = new QueryWrapper<>();
        scenicOrderCollectionQueryWrapper.eq("is_deleted",0);
        scenicOrderCollectionQueryWrapper.eq("id",scenicOrderCollectionConfirmationReq.getId());
        LocalFunOrderCollection scenicOrderCollection = scenicOrderCollectionMapper.selectOne(scenicOrderCollectionQueryWrapper);
        scenicOrderCollection.setGmtModified(LocalDateTime.now());
        scenicOrderCollection.setModifiedId(user.getId());
        scenicOrderCollection.setStatus(OrderCollectionStatus.UN_REJECT.getCode());
        scenicOrderCollection.setRejectInfo("");
        scenicOrderCollectionMapper.updateById(scenicOrderCollection);

        //財務-再次確認
        if(StringUtils.isNotBlank(scenicOrderCollection.getCollectionNumber())){
            BillOperateRefundReq billOperateRefundReq = new BillOperateRefundReq();
            billOperateRefundReq.setBillNumber(scenicOrderCollection.getCollectionNumber());
            billOperateRefundReq.setBusinessType(SystemBusinessType.LOCAL_FUN.getCode());
            billOperateRefundReq.setUserId(user.getId());
            iFinanceBillService.reConfirm(billOperateRefundReq);
        }

        return Result.success(scenicOrderCollection.getOrderId());
    }

    @Override
    public Result rejectPayment(String collectionNumber, Long userId, String msg) {
        log.info("【当地玩乐订单收款-财务驳回收款】方法入参,number:{},msg:{},userId:{}", collectionNumber, msg, userId);
        LocalFunOrderCollection localFunOrderCollection = scenicOrderCollectionMapper.selectOne(Wrappers.<LocalFunOrderCollection>lambdaQuery()
                .eq(LocalFunOrderCollection::getCollectionNumber, collectionNumber)
                .eq(LocalFunOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode()));
        if (localFunOrderCollection == null) {
            //收款记录不存在
            return Result.failed(SystemError.LOCAL_FUN_18023);
        }
        localFunOrderCollection.setStatus(OrderCollectionStatus.REJECT.getCode());
        localFunOrderCollection.setRejectInfo(msg);
        localFunOrderCollection.setModifiedId(userId);
        localFunOrderCollection.setGmtModified(LocalDateTime.now());
        scenicOrderCollectionMapper.updateById(localFunOrderCollection);
        return Result.success();
    }
}
